#coding: utf-8
class CulturalHeritage::Tipology < ActiveRecord::Base
  default_scope where("deleted = 0")
  validates :group, :presence => {:message => "El Grupo es requerido"}
  validates :subGroup, :presence => {:message => "El Sub Grupo es requerido"}
  validates :name, :presence => {:message => "El nombre es requerido"}
  has_many :list_cultural_heritages, :class_name => 'CulturalHeritage::CulturalHeritage',  :foreign_key => 'tipology'
  belongs_to :obj_group, :class_name => 'CulturalHeritage::Group',  :foreign_key => 'group'
  belongs_to :obj_subGroup, :class_name => 'CulturalHeritage::SubGroup',  :foreign_key => 'subGroup'
  def str_group
    if group.blank?
      return ""
    else
      obj_group = CulturalHeritage::Group.find(group)
      return obj_group.name
    end
  end

  def str_subGroup
    if subGroup.blank?
      return ""
    else
      obj_subGroup = CulturalHeritage::SubGroup.find(subGroup)
      return obj_subGroup.name
    end
  end
  
  def self.count_group_dependencies(id)
      return find(:all,:conditions=>["cultural_heritage_tipologies.group = ? and (cultural_heritage_tipologies.deleted = ?) ",id,0],:select=>"count(*) as 'tipologies'")[0].tipologies.to_i
  end

  def self.count_subgroup_dependencies(id)
      return find(:all,:conditions=>["cultural_heritage_tipologies.subGroup = ? and (cultural_heritage_tipologies.deleted = ?) ",id,0],:select=>"count(*) as 'tipologies'")[0].tipologies.to_i
  end

  def erasable
    cultuheri = CulturalHeritage::CulturalHeritage.count_tipology_dependencies(id)
    if cultuheri >0
      return "Imposible borrar. Existen dependencias en patrimonio cultural/preregistro"          
    end
    return nil
  end
end
